package com.ny.service.impl;

import com.ny.entity.User;
import com.ny.mapper.UserMapper;
import com.ny.service.EmailService;
import com.ny.service.UserService;

import com.ny.until.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmailService emailService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public int addUser(User user) {
        // 把数据交给数据库之前先进行加密：MD5

          String  pwd = PasswordUtil.encryptPassword(user.getPassword());// 进行加密  pwd = gfalk;hgalkhg;
          user.setPassword(pwd);// 把加密的密码交给user
          return userMapper.addUser(user);
    }

    @Override
    public User findUser(String username, String password) {// 123456
        // 对密码进行加密
        String pwd = PasswordUtil.encryptPassword(password);// 对密码加密，123456变成一串字符
        return userMapper.findUser(username,pwd);// 把加密之后的密码以及用户名一起交给数据库
    }

    @Override
    public User findUserByEmail(String email) {
        return userMapper.findUserByEmail(email);
    }

    @Override
    public int updatePassword(String password, String email) {
        // 密码加密
        String pwd = PasswordUtil.encryptPassword(password);
        return userMapper.updatePassword(pwd,email);
    }
    // 给发件人发送验证码
    @Override
    public void sendToEmail(String toEmail) {
        // 获取验证码
        String code = emailService.getCode();
        // 执行发送验证码的逻辑
        emailService.sendEmail(toEmail,code);
        // 把验证码存储起来Redis中。
        ValueOperations<String, String> ops = redisTemplate.opsForValue();// 操作Redis, 把验证码存储起来
        ops.set(toEmail,code);// key value  toEmail- code
    }
    // 判断验证码是否正确，从输入的验证码跟Redis中取出的验证码进行比较
    @Override
    public boolean checkCode(String toEmail, String code) {// 输入的验证码和Redis中存储的验证码进行比较
        // 获取Redis中存储的验证码
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String redisCode = ops.get(toEmail);
        // 判断验证码是否一致
        return redisCode.equals(code);
    }



}
